﻿using JSLCloud.Models;
using Newtonsoft.Json;
using System;
using System.Configuration;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;

namespace JSLCloud.Utilities.WebApi
{
    /// <summary>
    /// Http Request Helper
    /// </summary>
    public static class HttpRequestHelper
    {
        /// <summary>
        /// App Config
        /// </summary>
        public static AppConfig2 AppCfg { get; set; } = new AppConfig2();
        //private static string ApiUrl = @"http://7052342dm2.yicp.fun:13553";//ConfigurationManager.AppSettings["ERPAPIURL"];
        //private static string ApiUrl = "";
        /// <summary>
        /// 发送Get请求，使用requestGet=Params
        /// </summary>
        /// <param name="url"></param>
        /// <param name="requestGet"></param>
        /// <returns></returns>
        public static string Get(string url,string requestGet,string apiUrl)
        {
            try
            {

                requestGet = requestGet ?? "";
                using (HttpClient client = new HttpClient())
                {
                    client.Timeout = TimeSpan.FromMinutes(5);
                    client.DefaultRequestHeaders.Add("x-token", AppCfg.Token);
                    client.DefaultRequestHeaders.Add("x-refresh-token", AppCfg.RefreshToken);
                    var response = client.GetAsync($"{apiUrl}{url}?requestObject={requestGet}").Result;
                    return response.Content.ReadAsStringAsync().Result; ;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 发送Get请求，使用requestObject=Params
        /// </summary>
        /// <param name="url"></param>
        /// <param name="requestGet"></param>
        /// <returns></returns>
        public static string GetObject(string url, string requestGet,string apiUrl)
        {
            try
            {

                requestGet = requestGet ?? "";
                using (HttpClient client = new HttpClient())
                {
                    client.Timeout = TimeSpan.FromMinutes(5);
                    client.DefaultRequestHeaders.Add("x-token", AppCfg.Token);
                    client.DefaultRequestHeaders.Add("x-refresh-token", AppCfg.RefreshToken);
                    var response = client.GetAsync($"{apiUrl}{url}?requestObject={requestGet}").Result;
                    return response.Content.ReadAsStringAsync().Result; ;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="url"></param>
        /// <param name="param"></param>
        /// <param name="requestGet"></param>
        /// <returns></returns>
        public static string Get(string url, string param, string requestGet, string apiUrl)
        {
            try
            {

                requestGet = requestGet ?? "";
                using (HttpClient client = new HttpClient())
                {
                    client.Timeout = TimeSpan.FromMinutes(5);
                    client.DefaultRequestHeaders.Add("x-token", AppCfg.Token);
                    client.DefaultRequestHeaders.Add("x-refresh-token", AppCfg.RefreshToken);
                    var response = client.GetAsync($"{apiUrl}{url}?{param}={requestGet}").Result;
                    return response.Content.ReadAsStringAsync().Result; ;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="url"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public static string GetWithParams(string url, string param, string apiUrl)
        {
            try
            {
                using (HttpClient client = new HttpClient())
                {
                    client.Timeout = TimeSpan.FromMinutes(5);
                    client.DefaultRequestHeaders.Add("x-token", AppCfg.Token);
                    client.DefaultRequestHeaders.Add("x-refresh-token", AppCfg.RefreshToken);
                    var response = client.GetAsync($"{apiUrl}{url}?{param}").Result;
                    return response.Content.ReadAsStringAsync().Result; ;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 发起POST请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postData"></param>
        /// <returns></returns>
        public static string Post(string url, string postData, string apiUrl)
        {
            try
            {
                postData = postData ?? "";
                using (HttpClient client = new HttpClient())
                {
                    client.Timeout = TimeSpan.FromMinutes(5);
                    using (HttpContent httpContent = new StringContent(postData, Encoding.UTF8))
                    {
                        httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                        httpContent.Headers.Add("x-token", AppCfg.Token);
                        httpContent.Headers.Add("x-refresh-token",AppCfg.RefreshToken);
                        HttpResponseMessage response = client.PostAsync($"{apiUrl}{url}", httpContent).Result;
                        var result = response.Content.ReadAsStringAsync().Result;
                        if (string.IsNullOrEmpty(result))
                            return response.StatusCode.ToString();
                       
                        return result;
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 发送PUT请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="putData"></param>
        /// <returns></returns>
        public static string Put(string url, string putData, string apiUrl)
        {
            try
            {
                putData = putData ?? "";
                using (HttpClient client = new HttpClient())
                {
                    client.Timeout = TimeSpan.FromMinutes(5);
                    using (HttpContent httpContent = new StringContent(putData, Encoding.UTF8))
                    {
                        httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                        httpContent.Headers.Add("x-token", AppCfg.Token);
                        httpContent.Headers.Add("x-refresh-token", AppCfg.RefreshToken);
                        HttpResponseMessage response = client.PutAsync($"{apiUrl}{url}", httpContent).Result;
                        var resutl = response.Content.ReadAsStringAsync().Result;
                        //检查Token是否过期
                        var returnModel = JsonConvert.DeserializeObject<ResponseObject<dynamic>>(resutl);
                        if (returnModel == null)
                            return null;
                        if (returnModel.Code == -3)
                        {
                            throw new Exception("Token已过期，请重新登录");
                        }
                        else if (returnModel.Code == -2)
                        {
                            AppCfg.Token = returnModel.Data.Token;
                            AppCfg.RefreshToken = returnModel.Data.RefreshToken;
                            //重新发送请求
                            return Put(url, putData,apiUrl);
                        }

                        return resutl;
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }

    public class AppConfig2
    {
        /// <summary>
        /// Token
        /// </summary>
        public string Token { get; set; }

        /// <summary>
        /// Refresh Token
        /// </summary>
        public string RefreshToken { get; set; }
    }
}
